<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class mredirect extends MY_Model {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
    public $mytable = "redirect";
    public $primaryKey = "redirect_id";
    public $resCode = "REDIRECT";

    function __construct() {
        parent::__construct();
    }

    function field() {
		$fieldData = array();
		$fieldData['redirect_link_from'] = '';
		$fieldData['redirect_link_to'] = '';
		$fieldData['redirect_type'] = 301;
		$fieldData['redirect_description'] = '';
		$fieldData['redirect_time_create'] = 0;
		$fieldData['redirect_time_update'] = 0;
		$fieldData['redirect_admin_create'] = 0;
		$fieldData['redirect_admin_update'] = 0;
		$fieldData['redirect_status'] = 1;
		return $fieldData;
    }
	
	function run()
	{
		if(!file_exists("./mcache/redirect_link.php")) return '';
		$links = include_once("./mcache/redirect_link.php");
		$uri = implode('/', $this->uri->segments);
		if(isset($links) && $links)
		{
			
			foreach($links as $link)
			{
				$key = $link['redirect_link_from'];
				$link_redirect = false;
				$val = $link['redirect_link_to'];
				// Convert wild-cards to RegEx
				$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));
				// Does the RegEx match?
				if (preg_match('#^'.$key.'$#', $uri))
				{
					$link_redirect = $val;
					// Do we have a back-reference?
					if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
					{
						$val = preg_replace('#^'.$key.'$#', $val, $uri);
						$link_redirect = $val;
					}
				}
				
				if($link_redirect)
				{
					if($link['redirect_type'] == 301)
					{
						// with 301 redirect
						redirect($link['redirect_link_to'], 'location', 301);
					}
					else
					{
						redirect($link['redirect_link_to'], $link['redirect_type']);
					}
				}
			}
		}
	}
	
	function rebuild_cache_file()
	{
		$file = './mcache/redirect_link.php';
		$this->load->helper('file');
		$this->db->select('redirect_link_from,redirect_link_to, redirect_type');
		$this->db->where('redirect_status >',0);
		$link = $this->db->from($this->mytable)->get()->result_array();
		if($link)
		{
			$data_temp =array();
		$data = "<?php \n";
        $data.="return ";
		 
			 $data_temp = $link;
			$data_temp = var_export($data_temp, true);
			$data.= $data_temp;
			$data.="?>\n";
			
			if ( ! write_file($file, $data))
			{
				 echo 'Unable to write the file';
			}
			else
			{
				 echo 'File written!';
			}
		}
	}
}

?>